import tkinter as tk    
from tkinter import filedialog    
from PIL import Image, ImageTk    
import random    
  
class LineDrawApp:    
    def __init__(self, master):    
        self.master = master    
        master.title("Line Draw App")    
        
        self.select_image() 
        self.width, self.height = self.image.size 
        self.canvas = tk.Canvas(master, width=self.width, height=self.height)  # 调整画布大小   
        self.canvas.pack(side=tk.LEFT)    
            
        self.copy_image_to_canvas()  # 调整顺序，先复制图像再创建画布  
        self.startx = 0
        self.line_steps = 0
        self.starty = 0
        self.row_steps = 0
        self.draw_line()    
        self.master.mainloop()    
    
    def select_image(self):    
        file_path = filedialog.askopenfilename()    
        if file_path:    
            self.image = Image.open(file_path)    
            self.image_tk = ImageTk.PhotoImage(self.image)    
            #self.image_label = tk.Label(self.master, image=self.image_tk)    
            #self.image_label.pack(side=tk.LEFT)    
               
    def copy_image_to_canvas(self):    
        # 计算画布上图片的位置，使其居中显示  
        x = 0  # 调整x坐标以居中显示图像  
        y = 0  # 调整y坐标以适应画布高度  
        # 将左侧图片绘制到右侧画布上    
       
        self.canvas.create_image(x, y, anchor=tk.NW, image=self.image_tk)    
        self.canvas.update()    
    
    def draw_line(self):    
        # 更新线条的起始和结束坐标，使其与左侧图片对齐            
        x1 = self.startx # 调整x1坐标以适应画布宽度         
        y1 = self.starty # 修改为从0开始，确保线条在图片范围内    
        
        x2 = x1 + self.line_steps # 调整x2坐标以适应画布宽度  
        self.line_steps += 2
        if self.line_steps >= self.canvas.winfo_width():
            self.line_steps = 0
            self.starty += 10
        y2 = y1 # 修改为从0开始，确保线条在图片范围内    
        # 在右侧画布上绘制线条    
        print(x1,y1,x2,y2)
        self.canvas.create_line(x1, y1, x2, y2,fill="red")  # 在右侧画布上绘制线条    
        self.canvas.update()  # 更新画布显示    
        # 每1秒更新一次线条位置，与左侧保持一致    
        self.master.after(30, self.draw_line)  # 每1秒更新一次线条位置
if __name__ == "__main__":    
    app = LineDrawApp(tk.Tk())